<template>
	<div class="form-area">
		<el-form ref="addForm" :model="addForm" :rules="rules" label-width="100px" style="width: 100%; height:auto;">
			<div class="form-title">
				<h3>{{isDetails ? '' : '选择'}}商品单位</h3>
				<span v-if="skuList.length == 0 && !isDetails">您还未添加sku，请先完成第二步编辑商品规格SKU！</span>
			</div>

			<div class="unit-list" v-if="isDetails">
				<el-tag v-for="item of productUnitSelectList" :key="item.id">
					单位：{{ item.unitName }}<template v-if="item.isSkuPack">（库存单位）</template>，转换系数：{{ item.ratio }}
				</el-tag>
			</div>

			<div class="unit-list" v-if="!isDetails">
				<div class="unit-item" v-for="item of productUnitList" :key="item.id">
					<el-checkbox v-model="item.selected" border @change="chooseUnit(item)" :disabled="skuList.length == 0">
						单位：{{ item.unitName }}<template v-if="item.isSkuPack">（库存单位）</template>，转换系数：{{ item.ratio }}
					</el-checkbox>
				</div>
			</div>

			<div class="form-title">
				<h3>SKU销售明细</h3>
			</div>

			<!-- <div class="table-header" v-if="!isDetails">
				<el-button type="primary" size="medium" @click="refreshTableData">刷新表格</el-button>
			</div> -->

			<el-table :data="tableData" stripe border style="width: 100%; margin-bottom: 20px;">
				<el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
				
				<el-table-column label="单位" prop="unitName" width="60"></el-table-column>
				<el-table-column label="图片" width="82">
					<template slot-scope="scope">
						<el-image :src="scope.row.skuThumbImage" style="width: 60px; height: 60px;"></el-image>
					</template>
				</el-table-column>
				
				<el-table-column label="SKU编码" prop="skuCode"></el-table-column>
				<el-table-column label="SKU名称" prop="skuName" width="100"></el-table-column>
				<el-table-column label="SKU条形码" prop="productBarCode" width="150">
					<template slot-scope="scope">
						<el-input v-model="scope.row.productBarCode" style="width:100%" placeholder="请输入条形码" :readonly="isDetails || scope.row.isSkuPack === 1"></el-input>
					</template>
				</el-table-column>
				
				<el-table-column label="销售渠道" prop="saleChannel" width="140">
					<template slot-scope="scope">
						<span v-if="isDetails">{{scope.row.saleChannel == 1 ? '商家/供应商' : scope.row.saleChannel == 2 ? '直播平台' : '微信小程序'}}</span>
						<el-select v-model="scope.row.saleChannel" placeholder="选择销售渠道" style="width: 100%;" v-else>
							<el-option label="微信小程序" value="0"></el-option>
							<el-option label="商家/供应商" value="1"></el-option>
							<el-option label="直播平台" value="2"></el-option>
						</el-select>
					</template>
				</el-table-column>
				
				<el-table-column label="原价(划线价)" prop="priceShow" width="110">
					<template slot-scope="scope">
						<el-input v-model="scope.row.priceShow" style="width:100%" placeholder="请输入原价" :readonly="isDetails || scope.row.isSkuPack === 1"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="销售价(元)" prop="price" width="110">
					<template slot-scope="scope">
						<el-input v-model="scope.row.price" style="width:100%" placeholder="请输入销售价" :readonly="isDetails || scope.row.isSkuPack === 1"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="会员价(元)" prop="memberPrice" width="110">
					<template slot-scope="scope">
						<el-input v-model="scope.row.memberPrice" style="width:100%" placeholder="请输入会员价" :readonly="isDetails || scope.row.isSkuPack === 1"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="券抵扣金额(元)" prop="couponAmount" width="120">
					<template slot-scope="scope">
						<el-input v-model="scope.row.couponAmount" style="width:100%" placeholder="请输入金额" :readonly="isDetails || scope.row.isSkuPack === 1"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="充值会员价(元)" prop="rechargePrice" width="120">
					<template slot-scope="scope">
						<el-input v-model="scope.row.rechargePrice" style="width:100%" placeholder="请输入价格" :readonly="isDetails"></el-input>
					</template>
				</el-table-column>
				
				<el-table-column label="展示分类" prop="status" width="140">
					<template slot-scope="scope">
						<span v-if="isDetails">{{scope.row.showType}}</span>
						<el-cascader v-model="scope.row.showTypeId" :options="categoryTree" :props="{ value: 'id', label: 'categoryName' }" @change="val => {changeCategory(val, scope.$index)}" placeholder="选择分类" style="width: 100%;" v-else></el-cascader>
					</template>
				</el-table-column>
				
				<el-table-column label="是否关联库存" prop="stockStatus" width="120">
					<template slot-scope="scope">
						<span v-if="isDetails">{{scope.row.stockStatus ? '是' : '否'}}</span>
						<template v-else>
							<el-radio-group v-model="scope.row.stockStatus">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="0">否</el-radio>
							</el-radio-group>
						</template>
					</template>
				</el-table-column>
				
				<el-table-column label="状态" prop="status" width="50">
					<template slot-scope="scope">
						<span>{{scope.row.status == 1 ? '上架' : '下架'}}</span>
					</template>
				</el-table-column>
				<el-table-column label="状态" prop="status" width="70">
					<template slot-scope="scope">
						<span v-if="scope.row.saleStatus == 1">在售中</span>
						<span style="color: #f00;" v-else>已停售</span>
					</template>
				</el-table-column>
				
				<el-table-column label="操作" prop="saleStatus" width="84" v-if="!isDetails">
					<template slot-scope="scope">
						<div>
							<el-button type="warning" size="mini" v-if="scope.row.saleStatus" @click="stopSale(scope.row)">停售</el-button>
							<el-button type="success" size="mini" v-if="!scope.row.saleStatus" @click="startSale(scope.row)">启售</el-button>
						</div>
						<div style="margin-top: 5px;">
							<el-button type="info" size="mini" @click="delectSkuSale(scope.$index, scope.row)">移除</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>

			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item>
						<div class="form-submit">
							<el-button class="form-cancle-btn" :disabled="loading" @click="prev">上一步</el-button>
							<el-button class="form-submit-btn" :disabled="loading" type="primary" @click="onSubmit()" v-if="!isDetails">保存</el-button>
							<el-button class="form-cancle-btn" :disabled="loading" @click="closePage" v-if="isDetails">返回</el-button>
							<el-button class="form-cancle-btn" :disabled="loading" @click="next">下一步</el-button>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script>
	import { ossDomain } from '@api/sys.common'
	import { findProductUnitListByProductId } from '@api/product/product'
	import { findProductSkuSelf } from '@api/product/productSku'
	import { findAllProductSkuSaleList, save, stopSaleProductSkuSale, onSaleProductSkuSale, delProductSkuSale } from '@api/product/productSkuSale'
	export default {
		props: {
			isDetails: {
				type: Boolean,
				default: false
			},
			productDetails: Object,
			categoryTree: Array, //展示分类
		},
		data() {
			return {
				productId: 0, // 商品id
				productUnitList: [], // 商品单位列表
				productUnitSelectList: [], // 已选商品单位列表
				skuList: [], // 商品全部sku列表

				tableData: [], // 表格数据

				addForm: {},
				rules: {},

				gotoNext: false,
				loading: false,
			}
		},
		methods: {
			initData() { //初始化页面数据
				this.productUnitList = [];
				this.productUnitSelectList = [];
				this.skuList = [];
				this.tableData = [];
				
				this.getTableData(); //获取已经添加的销售sku
				this.getSkuDetails(); //获取商品规格sku
			},
			
			getTableData() { // 获取表格数据（销售sku列表）
				findAllProductSkuSaleList({ productId: this.productId })
					.then(res => {
						let list = res.data;
						
						list.forEach(item => {
							// 整理分类
							let showTypeId = [];
							let showType = '';
							for(let i = 0; i < this.categoryTree.length; i++) {
								if(this.categoryTree[i].children !== undefined) {
									for(let j = 0; j < this.categoryTree[i].children.length; j++) {
										if(this.categoryTree[i].children[j].id == item.showTypeId) {
											showTypeId.push(this.categoryTree[i].id, this.categoryTree[i].children[j].id);
											showType = this.categoryTree[i].categoryName + '-' + this.categoryTree[i].children[j].categoryName;
											break;
										}
									}
								}
							}
							
							// 汇总参数
							this.tableData.push({
								id: item.id,
								productId: item.productId, // 商品信息
								productName: item.productName,
								productCode: item.productCode,
								productBarCode: item.productBarCode,
								priceShow: item.priceShow,
								price: item.price,
								memberPrice: item.memberPrice,
								couponAmount: item.couponAmount,
								rechargePrice: item.rechargePrice ? item.rechargePrice : '',
								productUnitId: item.productUnitId, // 单位信息
								unitName: item.unitName,
								isSkuPack: item.isSkuPack,
								ratio: item.ratio,
								saleStatus: item.saleStatus, // 单位售卖状态
								skuId: item.skuId, // sku信息
								skuCode: item.skuCode,
								skuName: item.skuName,
								status: item.status, // 状态 1.上架 0.下架（同步SKU状态）
								stockStatus: item.stockStatus,
								skuThumbImage: item.skuThumbImage,
								showType: this.isDetails ? showType : item.showType,
								showTypeId: this.isDetails ? item.showTypeId : showTypeId,
								saleChannel: item.saleChannel ? item.saleChannel.toString() : '0',
							})
						});
						
						this.getUnitDetails(); // 获取商品单位列表
					})
			},
			getSkuDetails() { // 获取sku
				findProductSkuSelf({ productId: this.productId })
					.then(res => {
						this.skuList = res.data.skuVoList;
					})
			},
			
			getUnitDetails() { // 获取单位
				findProductUnitListByProductId({ productId: this.productId })
					.then(res => {
						this.productUnitList = res.data;
						this.productUnitList.forEach(item => {
							this.$set(item, 'selected', false);
						});

						this.dealUnitData(); // 整理单位数据
					})
			},
			dealUnitData() { // 整理单位数据（展示类型、已选单位）
				this.tableData.forEach(item => {
					this.productUnitList.forEach(unit => {
						if (unit.id == item.productUnitId) {
							unit.selected = true;
							this.initSelectUnitData(unit);
						}
					})
				})
			},
			initSelectUnitData(unit) {
				let hasUnit = false;
				this.productUnitSelectList.forEach(item => {
					if (item.id == unit.id) {
						hasUnit = true;
					}
				});
				if (!hasUnit) {
					this.productUnitSelectList.push(unit);
				}
			},

			chooseUnit(item) { // 选择单位
				if (this.skuList.length == 0) {
					item.selected = false;
					this.$alert('您还未添加sku，请先完成第二步编辑商品规格SKU！', '温馨提示', {
						confirmButtonText: '确定',
						callback: () => {
							this.prev();
						}
					})
				} else {
					if (item.selected) { // 选中
						this.setTableData(item);
					} else { // 取消选中
						let isHasUnit = false // 判断该单位下是否有sku明细
						for (let i in this.tableData) {
							if (this.tableData[i].unitName == item.unitName) {
								isHasUnit = true;
								break;
							}
						}

						if (isHasUnit) { // 如果有sku明细，弹出提示
							this.$alert(`如要移除单位【${item.unitName}】，请先手动删除该单位下已有的sku明细！`, '温馨提示', {
									confirmButtonText: '确定',
									type: 'warning'
								})
								.then(() => {
									item.selected = true;
								})
						}
					}
				}
			},
			setTableData(item) { // 添加表格数据
				this.skuList.forEach(sku => {
					if (sku.status) {
						this.tableData.push({
							productId: this.productId, // 商品信息
							productName: this.productDetails.productName,
							productCode: this.productDetails.productCode,
							productBarCode: item.isSkuPack ? sku.productBarCode : '',
							priceShow: item.isSkuPack ? sku.priceShow : '',
							price: item.isSkuPack ? sku.price : '',
							memberPrice: item.isSkuPack ? sku.memberPrice : '',
							couponAmount: item.isSkuPack ? sku.couponAmount : '',
							rechargePrice: sku.rechargePrice ? sku.rechargePrice : '',
							productUnitId: item.id, // 单位信息
							unitName: item.unitName,
							isSkuPack: item.isSkuPack,
							ratio: item.ratio,
							saleStatus: 1, // 单位售卖状态
							skuId: sku.skuId, // sku信息
							skuCode: sku.productSkuCode,
							skuName: sku.skuName,
							status: sku.status, // 状态 1.上架 0.下架（同步SKU状态）
							stockStatus: 0, //默认0
							skuThumbImage: sku.thumbImage,
							showType: '',
							showTypeId: '',
							saleChannel: '0',
						});
					}
				})
			},
			delectTableData(item) { // 移除表格数据
				let index = 0; // 起始下标
				for (let i in this.tableData) {
					if (this.tableData[i].productUnitId == item.id) {
						index = i;
						break;
					}
				}
				let length = 0; // 长度
				for (let i in this.tableData) {
					if (this.tableData[i].productUnitId == item.id) {
						length++;
					}
				}
				this.tableData.splice(index, length);
			},
			
			refreshTableData() { // 刷新表格
				let list = [];
				this.productUnitList.forEach(unit => {
					if (unit.selected) {
						this.skuList.forEach(sku => {
							if (sku.status && !this.checkHasSku(unit, sku)) {
								list.push({
									productId: this.productId, // 商品信息
									productName: this.productDetails.productName,
									productCode: this.productDetails.productCode,
									productBarCode: unit.isSkuPack ? sku.productBarCode : '',
									priceShow: unit.isSkuPack ? sku.priceShow : '',
									price: unit.isSkuPack ? sku.price : '',
									memberPrice: unit.isSkuPack ? sku.memberPrice : '',
									couponAmount: unit.isSkuPack ? sku.couponAmount : '',
									rechargePrice: sku.rechargePrice ? sku.rechargePrice : '',
									productUnitId: unit.id, // 单位信息
									unitName: unit.unitName,
									isSkuPack: unit.isSkuPack,
									ratio: unit.ratio,
									saleStatus: 1, // 单位售卖状态
									skuId: sku.skuId, // sku信息
									skuCode: sku.productSkuCode,
									skuName: sku.skuName,
									status: sku.status, // 状态 1.上架 0.下架（同步SKU状态）
									stockStatus: 0,
									skuThumbImage: sku.thumbImage,
									showType: '',
									showTypeId: '',
									saleChannel: '0'
								});
							}
						});
					}
				});

				this.tableData = this.tableData.concat(list);
			},
			checkHasSku(unit, sku) { // 判断是否有对应的sku
				let check = false;
				for (let i in this.tableData) {
					if (this.tableData[i].skuName == sku.skuName && this.tableData[i].unitName == unit.unitName) {
						check = true;
						break;
					}
				}

				return check;
			},

			changeCategory(value, index) { // 选择销售分类
				// this.tableData[index].showTypeId = value[1];
				
				this.categoryTree.forEach(item1 => {
					if(item1.id == value[0]) {
						item1.children.forEach(item2 => {
							if(item2.id == value[1]) {
								this.tableData[index].showType = item2.categoryName;
							}
						})
					}
				})
			},
			
			delectSkuSale(index, item) { // 删除sku销售
				this.$confirm(`您是否确认删除SKU销售【名称：${item.skuName}，单位：${item.unitName}？】`, '温馨提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						if (item.id) {
							delProductSkuSale({
									id: item.id
								})
								.then(() => {
									this.$message.success('删除成功');

									// 删除表格里对应的sku销售
									this.tableData.splice(index, 1);
								})
						} else {
							this.$message.success('删除成功');
							this.tableData.splice(index, 1);
						}
					})
			},

			stopSale(item) {
				// if (item.id === '' || item.id === undefined) {
				// 	this.$message.success('停售成功！')
				// 	item.saleStatus = 0
				// 	return false
				// }

				stopSaleProductSkuSale({ id: item.id })
					.then(() => {
						this.$message.success('停售成功！');
						item.saleStatus = 0;
					})
			},
			startSale(item) {
				// if (item.id === '' || item.id === undefined) {
				// 	this.$message.success('启售成功！')
				// 	item.saleStatus = 1
				// 	return false
				// }
				onSaleProductSkuSale({ id: item.id })
					.then(() => {
						this.$message.success('启售成功！');
						item.saleStatus = 1;
					})
			},

			next() {
				// 下一步
				if (this.isDetails) {
					this.$emit('next', 3);
				} else {
					this.gotoNext = true;
					this.onSubmit();
				}
			},
			prev() {
				// 上一步
				this.$emit('step', 1);
			},
			closePage() {
				// 返回列表
				this.$emit('close');
			},

			onSubmit() {
				if (this.tableData.length == 0) {
					this.$message.warning('请选择商品单位！')
					return
				}
				for (let i in this.tableData) {
					if (this.tableData[i].productBarCode === '') {
						this.$message.warning('SKU条形码不能为空！')
						return
					}
					if (this.tableData[i].productBarCode.length > 18) {
						this.$message.warning('SKU条码长度不允许超过18位！')
						return
					}
					let regExp = /^(?:0|[1-9]\d*)(?:\.\d*[1-9])?$/
					if (this.tableData[i].priceShow === '') {
						this.$message.warning('原价不能为空！')
						return
					}
					if (!regExp.test(this.tableData[i].priceShow)) {
						this.$message.warning('原价格式不正确！')
						return false
					}
					if (this.tableData[i].price === '') {
						this.$message.warning('销售价不能为空！')
						return
					}
					if (!regExp.test(this.tableData[i].price)) {
						this.$message.warning('销售价格式不正确！')
						return false
					}
					if (this.tableData[i].memberPrice === '') {
						this.$message.warning('会员价不能为空！')
						return
					}
					if (!regExp.test(this.tableData[i].memberPrice)) {
						this.$message.warning('会员价格式不正确！')
						return false
					}
					if (this.tableData[i].couponAmount === '') {
						this.$message.warning('券抵扣金额不能为空！')
						return
					}
					if (!regExp.test(this.tableData[i].couponAmount)) {
						this.$message.warning('券抵扣金额格式不正确！')
						return false
					}
					if (!regExp.test(this.tableData[i].rechargePrice)) {
						this.$message.warning('充值会员价格式不正确！')
						return false
					}
					if (this.tableData[i].showTypeId === '') {
						this.$message.warning('请选择展示分类！')
						return
					}
					if (this.tableData[i].stockStatus === '') {
						this.$message.warning('请选择是否关联库存！')
						return
					}

					for (let j in this.tableData) {
						if (i != j) {
							if (this.tableData[i].productBarCode == this.tableData[j].productBarCode) {
								this.$message.warning('SKU条码重复，请手动移除重复的数据或修改SKU条码！')
								return
							}
						}
					}
				}
				this.$refs.addForm.validate(valid => {
					if (valid) {
						this.loading = true;
						let params = this.objDeepCopy(this.tableData)
						params.forEach(item => {
							item.showTypeId = item.showTypeId[1]
						});
						save(params)
							.then(() => {
								this.$message.success('保存成功')
								this.loading = false

								if (this.gotoNext) {
									this.$emit('next', 3)
									this.gotoNext = false
								} else {
									this.$emit('close')
								}
							})
							.catch(() => {
								this.loading = false
								this.gotoNext = false
							})
					} else {
						this.loading = false
						this.gotoNext = false
					}
				})
			},
			objDeepCopy(source) { // 深拷贝数组or对象
				let sourceCopy = source instanceof Array ? [] : {};
				for (let item in source) {
					sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item];
				}
				return sourceCopy;
			}
		},
		mounted() {
			// 获取表单数据
			if (sessionStorage.getItem('productId')) {
				this.productId = parseInt(sessionStorage.getItem('productId'))
				// this.getSkuDetails();
				// this.getTableData();
			}

			this.imgUrlHeader = ossDomain;
		}
	}
</script>

<style lang="scss" scoped>
	.form-area {
		.form-title {
			justify-content: flex-start;
			align-items: center;

			span {
				font-size: 12px;
				color: #f00;
				margin-left: 20px;
			}
		}

		.unit-list {
			width: 100%;
			flex-wrap: wrap;
			display: flex;

			.unit-item {
				flex: 0 0 330px;
				margin-right: 40px;
				margin-top: 5px;

				.el-checkbox.is-bordered {
					width: 100%;
				}
			}

			.el-tag {
				margin-right: 30px;
			}
		}
	}
	
	.el-table {
		.el-radio {
			margin-right: 14px;
			&:last-child {
				margin-right: 0;
			}
		}
	}
</style>